package ru.yermak.bookkeeping.currency;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ru.yermak.bookkeeping.common.BookkeeperState;
import ru.yermak.bookkeeping.model.Currency;
import ru.yermak.bookkeeping.ui.DataTableModel;

/**
 * User: harrier
 * Date: Aug 11, 2008
 */
@Scope("singleton")
@Component
public class CurrencyTableModel extends DataTableModel<Currency> {

    private final Log log = LogFactory.getLog(this.getClass());
    
    private BookkeeperState bookkeeperState;
    private CurrencyDao currencyDao;

    private enum ColumnName {
        code, rate, name, original
    }

    @Autowired
    public CurrencyTableModel(BookkeeperState bookkeeperState, CurrencyDao currencyDao) {
        this.bookkeeperState = bookkeeperState;
        this.currencyDao = currencyDao;
    }

    public String getColumnName(int column) {
        return ColumnName.values()[column].toString();
    }


    public int getColumnCount() {
        return 4;
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        Currency currency = getData().get(rowIndex);
        switch (columnIndex) {
            case 0:
                return currency.getCode();
            case 1:
                return currency.getRate();
            case 2:
                return currency.getName();
            case 3:
                return currency.isOriginal();
            default:
                throw new IllegalArgumentException("Column index=" + columnIndex);
        }
    }


    @Transactional(propagation = Propagation.REQUIRED)
    public void load() {
        setData(currencyDao.findCurrencyByUserId(bookkeeperState.getUserId()));
        this.fireTableDataChanged();
    }

    public void clean() {
        rowCount = 0;
        data = null;
    }
}
